package marchsoft.modules.selfFish.pisciculture.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.selfFish.pisciculture.entity.CommunityCommunication;
import marchsoft.modules.selfFish.pisciculture.entity.SysThumbsUp;
import marchsoft.modules.selfFish.pisciculture.entity.dto.CommunityCommunicationDto;
import marchsoft.modules.selfFish.pisciculture.entity.vo.CommunityCommunicationVo;
import marchsoft.modules.selfFish.pisciculture.mapper.CommunityCommunicationMapper;
import marchsoft.modules.selfFish.pisciculture.service.CommunityCommunicationService;
import marchsoft.modules.selfFish.pisciculture.service.ISysThumbsUpService;
import marchsoft.modules.system.entity.SysRelationFile;
import marchsoft.modules.system.service.ISysRelationFileService;
import marchsoft.response.Result;
import marchsoft.utils.FileUtils;
import marchsoft.utils.SecurityUtils;
import marchsoft.utils.ServiceType;
import marchsoft.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 *@title CommunityCommunicationServiceImpl
 *@description
 *@author Lenovo
 *@version 1.0
 *@create 2024-07-15 17:30
 */
@Service
@Slf4j
public class CommunityCommunicationServiceImpl extends ServiceImpl<CommunityCommunicationMapper, CommunityCommunication> implements CommunityCommunicationService {

    @Autowired
    private CommunityCommunicationMapper communityCommunicationMapper;

    @Autowired
    private CommunityCommunicationService communityCommunicationService;

    @Autowired
    private ISysThumbsUpService thumbsUpService;

    @Autowired
    private ISysRelationFileService sysRelationFileService;
    @Override
    public Result<Object> getCommunityCommunicationList(String content, Long pageNum, Long pageSize) {
        IPage<CommunityCommunicationVo> communityCommunicationList = communityCommunicationMapper.getCommunityCommunicationList(new Page<>(pageNum, pageSize), content);
        communityCommunicationList.getRecords().stream().forEach(communityCommunicationVo -> {
            QueryWrapper<SysThumbsUp>qw = new QueryWrapper<>();
            qw.eq("community_id",communityCommunicationVo.getId())
                    .eq("status", "1");
            List<SysThumbsUp> list = thumbsUpService.list(qw);
            if(list != null && list.size()>0){
                communityCommunicationVo.setIsThumbsUp(true);
            }else {
                communityCommunicationVo.setIsThumbsUp(false);
            }
            //附件
            QueryWrapper<SysRelationFile> qw1 = new QueryWrapper<>();
            qw1.eq("service_id",communityCommunicationVo.getId())
                    .eq("status","1")
                    .eq("service_type", getContentType(communityCommunicationVo.getContentType()));
            List<SysRelationFile> fileList = sysRelationFileService.list(qw1);
            if(fileList != null && fileList.size()>0){
                communityCommunicationVo.setFileList(fileList);
            }
        });
        return Result.success(communityCommunicationList);
    }

    @Override
    public Result<Object> create(CommunityCommunicationDto communityCommunicationDto) {
        CommunityCommunication communityCommunication = new CommunityCommunication();
        BeanUtils.copyProperties(communityCommunicationDto,communityCommunication);
        communityCommunication.setCreatedUserId(SecurityUtils.getCurrentUserId());
        communityCommunication.setCreatedTime(LocalDateTime.now());
        communityCommunication.setStatus(true);
        if(communityCommunicationMapper.insert(communityCommunication)>0){
            List<Long>fileIds = communityCommunicationDto.getFileIds();
            if(fileIds != null && fileIds.size()>0){
                for (Long fileId : fileIds){
                    //附件保存
                    sysRelationFileService.saveFile(fileId,communityCommunication.getId(), getContentType(communityCommunication.getContentType()));
                }
            }
            log.info(StrUtil.format("【添加养鱼知识库成功】操作人id：{}，新增目标communityCommunication：{}", SecurityUtils.getCurrentUserId(), communityCommunicationDto));
            return Result.success("新增成功！");
        };
        return Result.error("新增失败！");
    }

    @Override
    public Result<Object> delete(Set<Long> ids) {
        UpdateWrapper<CommunityCommunication> uw = new UpdateWrapper<>();
        uw.in("id",ids)
                .set("status",false);
        if(communityCommunicationService.update(uw)){
            log.info(StrUtil.format("【删除养鱼知识库成功】操作人id：{}，删除目标communityCommunications：{}", SecurityUtils.getCurrentUserId(), ids.toString()));
            return Result.success("删除成功！");
        };
        return Result.error("删除失败！");
    }

    @Override
    public Result<Object> update(CommunityCommunicationDto communityCommunicationDto) {
        CommunityCommunication communityCommunication = getById(communityCommunicationDto.getId());
        if (ObjectUtil.isEmpty(communityCommunication)) {
            log.error(StrUtil.format("【修改养鱼知识库失败】操作人id：{}，修改目标communityCommunication为空，目标communityCommunicationId：{}", SecurityUtils.getCurrentUserId(), communityCommunication.getId()));
            throw new BadRequestException("修改失败，当前数据id不存在");
        }
        if(communityCommunication.getCreatedUserId()!=SecurityUtils.getCurrentUserId()){
            log.error(StrUtil.format("【修改养鱼知识库失败】操作人id：{}，目标communityCommunication新增人id：{}", SecurityUtils.getCurrentUserId(), communityCommunication.getCreatedUserId()));
            throw new BadRequestException("该养鱼知识库不是你新增的，不能修改：" + communityCommunicationDto.getId());
        }
        BeanUtils.copyProperties(communityCommunicationDto,communityCommunication);
        if(updateById(communityCommunication)){
            log.info(StrUtil.format("【修改养鱼知识库成功】操作人id：{}，修改目标communityCommunication：{}", SecurityUtils.getCurrentUserId(), communityCommunicationDto));
            return Result.success("修改成功！");
        };
        return Result.error("修改失败！");
    }

    @Override
    public void download(String content, HttpServletResponse response) throws IOException {
        Page page = new Page<>(-1, -1);
        List<CommunityCommunicationVo> records = communityCommunicationMapper.getCommunityCommunicationList(page, content).getRecords();
        List<Map<String, Object>> list = new ArrayList<>();
        records.forEach(communityCommunicationVo -> {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("内容", communityCommunicationVo.getContent());
            map.put("创建时间", LocalDateTimeUtil.format(communityCommunicationVo.getCreatedTime(), DatePattern.NORM_DATETIME_FORMATTER));
        });
        Map<Integer, Integer>widthMap = new HashMap<>();
        FileUtils.downloadExcel(list,widthMap, response);
    }

    @Override
    public Result<Object> addViewNum(Long id) {
        CommunityCommunication cc = getById(id);
        cc.setViewNum(cc.getViewNum()==null?1:cc.getViewNum()+1);
        if(updateById(cc)){
            return Result.success("浏览次数添加成功！");
        }
        return Result.error("浏览次数添加失败，请联系管理员！");
    }

    @Override
    public Result<Object> addThumbsUp(Long id) {
        CommunityCommunication cc = getById(id);
        cc.setThumbsUp(cc.getThumbsUp()==null?1:cc.getThumbsUp()+1);
        //添加点赞记录
        SysThumbsUp sysThumbsUp = new SysThumbsUp();
        sysThumbsUp.setCommunityId(id);
        sysThumbsUp.setCreatedUser(SecurityUtils.getCurrentUserId());
        sysThumbsUp.setCreatedTime(LocalDateTime.now());
        sysThumbsUp.setStatus("1");
        if(updateById(cc)){
            thumbsUpService.save(sysThumbsUp);
            return Result.success("点赞次数添加成功！");
        }
        return Result.error("点赞次数添加失败，请联系管理员！");
    }

    @Override
    public Result<Object> deleteThumbsUp(Long id) {
        CommunityCommunication cc = getById(id);
        cc.setThumbsUp(cc.getThumbsUp()-1);
        if(updateById(cc)){
            UpdateWrapper<SysThumbsUp>up = new UpdateWrapper<>();
            up.eq("community_id",id)
                    .eq("created_user",SecurityUtils.getCurrentUserId());
            up.set("status","0");
            thumbsUpService.update(up);
            return Result.success("点赞次数删除成功！");
        }
        return Result.error("点赞次数删除失败，请联系管理员！");
    }

    private String getContentType(String contentType){
        if("2".equals(contentType)){
            return ServiceType.PICTURE;
        }else if ("3".equals(contentType)){
            return ServiceType.AUDIO;
        } else if ("4".equals(contentType)) {
            return ServiceType.VIDEO;
        }
        return ServiceType.PICTURE;
    }
}
